﻿<?php if (!file_exists(__DIR__ . '/config.inc.php')): ?>
<?php
/**
 * Cola
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

/** 定义根目录 */
define('__COLA_DIR__', __DIR__);

/** 定义插件目录 */
define('__COLA_PLUGIN_PATH__', '/usr/plugins');

/** 定义模板目录 */
define('__COLA_THEME_PATH__', '/usr/themes');

/** 载入API支持 */
require_once __COLA_DIR__ . '/var/Common.php';

/** 程序初始化 */
Common::init();

/** 方便安装调试 */
Common::$debug = 2;
    
!is_dir(__COLA_DIR__.'/var/runtime') && mkdir(__COLA_DIR__.'/var/runtime', 0777);
	
else:

    header('Content-Type: UTF-8; charset=text/html', true);
	
    require_once __DIR__ . '/config.inc.php';

    //判断是否已经安装
    try {
        $installed = Db::instance()
		    ->select()
			->from('table.options')
			->where('name = ?', 'installed')
			->fetchRow();
        if (empty($installed) || $installed['value'] == 1) {
            Response::instance()->status(404);
			echo _e('安装程序检查到程序已经安装成功!');
            exit;
        }
    } catch (Exception $e) {
        // do nothing
    }

endif;

ob_start();

// 挡掉可能的跨站请求
if (!empty($_GET) || !empty($_POST)) {
    if (empty($_SERVER['HTTP_REFERER'])) {
        exit;
    }

    $parts = parse_url($_SERVER['HTTP_REFERER']);
	if (!empty($parts['port'])) {
        $parts['host'] = "{$parts['host']}:{$parts['port']}";
    }

    if (empty($parts['host']) || $_SERVER['HTTP_HOST'] != $parts['host']) {
        exit;
    }
}

/**
 * 获取传递参数
 *
 * @_r string $name 参数名称
 * @_r string $default 默认值
 * @return string
 */
function _r($name, $default = NULL) {
    return isset($_REQUEST[$name]) ?
        (is_array($_REQUEST[$name]) ? $default : $_REQUEST[$name]) : $default;
}

/**
 * 获取多个传递参数
 *
 * @return array
 */
function _rFrom() {
    $result = array();
    $_rs = func_get_args();

    foreach ($_rs as $_r) {
        $result[$_r] = isset($_REQUEST[$_r]) ?
            (is_array($_REQUEST[$_r]) ? NULL : $_REQUEST[$_r]) : NULL;
    }

    return $result;
}

/**
 * 输出传递参数
 *
 * @_r string $name 参数名称
 * @_r string $default 默认值
 * @return string
 */
function _v($name, $default = '') {
    echo _r($name, $default);
}

/**
 * 判断是否兼容某个环境(perform)
 *
 * @_r string $adapter 适配器
 * @return boolean
 */
function _p($adapter) {
    switch ($adapter) {
        case 'Pdo_Mysql':
            return Db_Pdo_Mysql::isAvailable();
        case 'Pdo_SQLite':
            //return Db_Pdo_SQLite::isAvailable();
        case 'Pdo_Pgsql':
            //return Db_Pdo_Pgsql::isAvailable();
        default:
            return false;
    }
}

/**
 * 获取url地址
 *
 * @return string
 */
function _u() {
    $url = Request::getUrlPrefix() . $_SERVER['REQUEST_URI'];
    if (isset($_SERVER['QUERY_STRING'])) {
        $url = str_replace('?' . $_SERVER['QUERY_STRING'], '', $url);
    }

    return dirname($url);
}

function message($msg = NULL)
{
	echo $msg;
    exit;
}

/**
 * 获取数据大小单位
 * @param int $byte 字节
 * @return string
 */
function get_byte($byte) {
	if($byte < 1024) {
		return $byte.' Byte';
	}elseif($byte < 1048576) {
		return round($byte/1024, 2).' KB';
	}elseif($byte < 1073741824) {
		return round($byte/1048576, 2).' MB';
	}elseif($byte < 1099511627776) {
		return round($byte/1073741824, 2).' GB';
	}else{
		return round($byte/1099511627776, 2).' TB';
	}
}

// 获取所在目录
function get_webdir() {
	$str = dirname($_SERVER['PHP_SELF']);
	if($str == '\\') return '/';
	if(strlen($str)>1) return $str.'/';
	else return '/';
}

/** 获取语言 */
$lang = _r('lang', Cookie::get('__lang'));
$langs = Widget_Options_General::getLangs();

if (empty($lang) || (!empty($langs) && !isset($langs[$lang]))) {
    $lang = 'zh_CN';
}

if ('zh_CN' != $lang) {
    $dir = defined('__COLA_LANG_DIR__') ? __COLA_LANG_DIR__ : __COLA_LANG_DIR__ . '/usr/langs';
    I18n::setLang($dir . '/' . $lang . '.mo');
}

Cookie::set('__lang', $lang);

$action = _r('action');
$method = strtoupper($_SERVER['REQUEST_METHOD']);

// 第一步，阅读
if(empty($action)) {
	
	include __COLA_DIR__ . "/var/install/view/index.php";
	
} elseif($action == 'env') {
	include __COLA_DIR__ . "/var/install/view/env.php";
} elseif($action == 'start' || $action == 'finish') {

    //$adapters = array('Mysql', 'Mysqli', 'Pdo_Mysql', 'SQLite', 'Pdo_SQLite', 'Pgsql', 'Pdo_Pgsql');
	$adapters = array('Pdo_Mysql');
    foreach ($adapters as $firstAdapter) {
        if (_p($firstAdapter)) {
            break;
        }
    }
    $adapter = _r('dbAdapter', $firstAdapter);
    !in_array($adapter, $adapters) && $adapter =  $adapters[0];

	if($action == 'start'){
        include __COLA_DIR__ . "/var/install/view/start.php";
		exit;
	} elseif($action == 'finish') {
		
	    if($method == 'GET') { 
		
		    message(_e('您没有执行安装步骤, 请您重新安装!'));
		
	    } elseif($method == 'POST') {

		$dbAdapter = $adapter;		
		$dbHost = _r('dbHost');	
		$dbUser = _r('dbUser');	
		$dbPassword = _r('dbPassword');
		$dbCharset = _r('dbCharset');
		$dbPort = _r('dbPort');
		$dbName = _r('dbName');	
		$dbPrefix = _r('dbPrefix');
		$dbEngine = _r('dbEngine');

		$userUrl = _r('userUrl');	
		$userName = _r('userName');	
		$userPassword = _r('userPassword');
		$userMail = _r('userMail');
		
		empty($dbAdapter) AND message(_e('dbAdapter_is_empty'));
		empty($dbHost) AND message(_e('dbHost_is_empty'));
		empty($dbUser) AND message(_e('dbUser_is_empty'));
		empty($dbPassword) AND message(_e('dbPassword_is_empty'));
		empty($dbCharset) AND message(_e('dbCharset_is_empty'));
		empty($dbPort) AND message(_e('dbPort_is_empty'));
		empty($dbName) AND message(_e('dbName_is_empty'));
		empty($dbPrefix) AND message(_e('dbPrefix_is_empty'));
		empty($userUrl) AND message(_e('请填写您的网站地址'));
		empty($userName) AND message(_e('请填写您的用户名'));
		//empty($userPassword) AND message(_e('userPassword_is_empty'));
		empty($userMail) AND message(_e('请填写您的邮箱地址'));
		
        /** 定义数据库参数 */
        $installDb = new Db($dbAdapter, $dbPrefix);
        $installDb->addServer(array(
            'host' => $dbHost,
            'user' => $dbUser,
            'password' => $dbPassword,
            'charset' => $dbCharset,
            'port' => $dbPort,
            'dbname' => $dbName,
        ), Db::READ | Db::WRITE);
        Db::setInstance($installDb);

        /** 检测数据库配置 */
        try {
            $installDb->query('SELECT 1=1')->affectedRows();
            } catch (Db_Exception $e) {
			
			$s = '安装程序捕捉到以下错误: 程序被终止, 请检查您的配置信息.<br><br>' . $e->getMessage();
			if(strstr($s,'[1049]')){
				$s = '数据库名错误';
			} else if(strstr($s,'[1045]')){
				$s = '数据库密码错误';
			} else if(strstr($s,'[1044]')){
				$s = '数据库帐户错误';
			}
			message($s);
        } catch (Db_Exception $e) {
            message(_t('安装程序捕捉到以下错误: " %s ". 程序被终止, 请检查您的配置信息.', $e->getMessage()));
        }

        $type = explode('_', $dbAdapter);
        $type = array_pop($type);
        $type = $type == 'Mysqli' ? 'Mysql' : $type;		
		
        $s = file_get_contents(__COLA_DIR__ . "/var/install/sql/{$type}.sql");
        $s = str_replace('{engine}', $dbEngine, $s);
        $s = str_replace('{pre}', $dbPrefix, $s);
        //$s = str_replace(";\r\n", ";\n", $s);
        $s = preg_replace('/#(.*?)\r\n/i', "", $s);
        $arr = explode(";\r\n", $s);

        foreach ($arr as $sql) {
            $sql = trim($sql);
            if (empty($sql)) {
                continue;
            }
            $arr = explode(";\n", $s);
            $installDb->query($sql)->affectedRows() === FALSE and message("sql: {$sql}");
        }

        $options = array(
	        array('name' => 'theme', 'value' => 'default'),
			array('name' => 'plugins', 'value' => 'a:0:{}'),
			array('name' => 'rewrite', 'value' => 0),
			array('name' => 'title', 'value' => 'Hello World'),
			array('name' => 'description', 'value' => 'Just So So ...'),
			array('name' => 'keywords', 'value' => 'php,blog'),
			array('name' => 'allowRegister', 'value' => 1),
			array('name' => 'timezone', 'value' => '28800'),
			array('name' => 'secret', 'value' => Common::randString(64)), 
	        array('name' => 'installed', 'value' => 1),
	        array('name' => 'siteUrl', 'value' => $userUrl),
			
			/** 可以配置单独的 CDN 域名：比如：http://upload.domain.com/upload/ */
			array('name' => 'uploadUrl', 'value' => $userUrl . '/usr/uploads'),
			array('name' => 'userCreateMailOpen', 'value' => '0'), 
			array('name' => 'userResetpwOpen', 'value' => '0'), 
			array('name' => 'beian', 'value' => ''),  
			array('name' => 'theme:default', 'value' =>  'a:2:{s:7:"logoUrl";N;s:12:"sidebarBlock";a:5:{i:0;s:15:"ShowRecentPosts";i:1;s:18:"ShowRecentComments";i:2;s:12:"ShowCategory";i:3;s:11:"ShowArchive";i:4;s:9:"ShowOther";}}'),
			array('name' => 'lang', 'value' => $lang),
			array('name' => 'charset', 'value' => _t('UTF-8')),
			array('name' => 'contentType', 'value' => 'text/html'),
			array('name' => 'gzip', 'value' => 0),
			array('name' => 'attachmentTypes', 'value' => '@image@'),
			array('name' => 'pageSize', 'value' => 5),
			array('name' => 'postsListSize', 'value' => 10),
			array('name' => 'postDateFormat', 'value' => 'Y-m-d'),
			array('name' => 'commentsPageSize', 'value' => 20),
			array('name' => 'commentsListSize', 'value' => 10),
			array('name' => 'commentsHTMLTagAllowed', 'value' => NULL),
			array('name' => 'commentsOrder', 'value' => 'ASC'),
			array('name' => 'commentDateFormat', 'value' => 'F jS, Y \a\t h:i a'),
			array('name' => 'commentsMaxNestingLevels', 'value' => 5),
			array('name' => 'commentsPostTimeout', 'value' => 24 * 3600 * 30),
			array('name' => 'commentsPageBreak', 'value' => 0),
			array('name' => 'commentsThreaded', 'value' => 1),
			array('name' => 'commentsPageDisplay', 'value' => 'last'),
			array('name' => 'commentsCheckReferer', 'value' => 0),
			array('name' => 'commentsAutoClose', 'value' => 0),
			array('name' => 'commentsPostIntervalEnable', 'value' => 1),
			array('name' => 'commentsPostInterval', 'value' => 60),
			array('name' => 'generator', 'value' => 'Cola ' . Common::VERSION),
			array('name' => 'actionTable', 'value' => 'a:0:{}'),
			array('name' => 'panelTable', 'value' => 'a:0:{}'),
			array('name' => 'routingTable', 'value' => serialize(array(
			'index' => array('url' => '/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'do' => array('url' => '/action/[action:alpha]', 'widget' => 'Widget_Do', 'action' => 'action'),
			'ucenter' => array('url' => '/ucenter/[action:alpha:0]', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'register' => array('url' => '/register', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'login' => array('url' => '/login', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'logout' => array('url' => '/logout', 'widget' => 'Widget_Archive'),		
			'tag' => array('url' => '/tag/[alias]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'author' => array('url' => '/author/[uid:digital]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'search' => array('url' => '/search/[keywords]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'index_page' => array('url' => '/page/[page:digital]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'tag_page' => array('url' => '/tag/[alias]/[page:digital]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'author_page' => array('url' => '/author/[uid:digital]/[page:digital]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'search_page' => array('url' => '/search/[keywords]/[page:digital]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'comment_page' => array('url' => '[permalink:string]/comment-page-[commentPage:digital]', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'feedback' => array('url' => '[permalink:string]/comment', 'widget' => 'Widget_Feedback', 'action' => 'action'), 
			'page' => array('url' => '/[alias].html', 'widget' => 'Widget_Archive', 'action' => 'render'),
			'post' => array('url' => '/archives/[cid]', 'widget' => 'Widget_Archive', 'action' => 'render'), 			
			'category' => array('url' => '/[alias]/', 'widget' => 'Widget_Archive', 'action' => 'render'), 
			'category_page' => array('url' => '/[alias]/[page:digital]/', 'widget' => 'Widget_Archive', 'action' => 'render')
			))),
		);
		
		/** 初始化全局变量 */
        foreach ($options as $value){
		    $installDb->insert('table.options')->values($value)->affectedRows();
		}
		
        /** 初始化分类 */
		$installDb->insert('table.metas')->values(array(
		    'name' => _t('默认分类'), 
			'alias' => 'default', 
			'type' => 'category',			
			'description' => _t('只是一个默认分类'),
			'contentsNum' => 1, 
			'order' => 0
		))->affectedRows();
		
        /** 初始化内容 */
		$installDb->insert('table.contents')->values(array(
		    'title' => _t('欢迎使用 Cola'), 
			'alias' => 'start',
            'type' => 'post',			
			'created' => Date::time(), 
			'modified' => Date::time(),
			'uid' => 1, 
			'mids' => '1', 
			'commentsNum' => 1, 
			'allowComment' => 1,
			'text' => _t('本页面由 Cola 创建, 这只是个测试页面.')
		))->affectedRows();

        /** 初始化关系 */
        $installDb->insert('table.relate')->values(array(
		    'mid' => 1, 
			'cid' => 1
		))->affectedRows();
		
        $installDb->insert('table.contents')->values(array(
		    'title' => _t('关于'), 
			'alias' => 'start-page',
            'type' => 'page',			
			'created' => Date::time(), 
			'modified' => Date::time(),
			'uid' => 1, 
			'mids' => '0', 
			'commentsNum' => 0, 
			'allowComment' => 1,
			'text' => _t('本页面由 Cola 创建, 这只是个测试页面.')
		))->affectedRows();
		
        /** 初始化评论 */
        $installDb->insert('table.comments')->values(array(
		    'uid' => 1,
		    'cid' => 1, 
			'created' => Date::time(), 
			'ownerId' => 1,
			'ip' => Request::instance()->longIp(), 
			'text' => '欢迎加入 Cola 大家族',
         	'parent' => 0		
		))->affectedRows();

        /** 初始化用户 */
        $password = empty($userPassword) ? substr(uniqid(), 7) : $userPassword;
        $installDb->insert('table.users')->values(array(
		    'name' => $userName, 
			'password' => Common::passwordHash($password), 
			'salt' => sha1(Common::randString(20)),
			'mail' => $userMail,
			'nickName' => $userName, 
			'group' => 'admin',
			'contentsNum' => 2,
            'commentsNum' => 1, 			
			'created' => Date::time(), 
			'logged' => Date::time(), 
			'activated' => Date::time()
		))->affectedRows();
		
        /** 初始化配置文件 */
        $lines = array_slice(file(__FILE__), 1, 25);
        $lines[] = "/** 定义数据库参数 */
\$db = new Db('$dbAdapter', '$dbPrefix');
\$db->addServer(array(
    'host' => '$dbHost',
    'user' => '$dbUser',
    'password' => '$dbPassword',
    'charset' => '$dbCharset',
    'port' => '$dbPort',
    'dbname' => '$dbName',
), Db::READ | Db::WRITE);
Db::setInstance(\$db);";

        $contents = implode('', $lines);
        if (!Common::isAppEngine()) {
            @file_put_contents('./config.inc.php', $contents);
        }

        if (!file_exists('./config.inc.php')) {
            message(_t('安装程序无法自动创建 <strong>config.inc.php</strong> 文件<br />您可以在网站根目录下手动创建 <strong>config.inc.php</strong> 文件, 并复制如下代码至其中<p><textarea rows="5" onmouseover="this.select();" class="w-100 mono" readonly>%s</textarea></p>', htmlspecialchars($contents)));
		}
		
        !is_dir(__COLA_DIR__.'/usr/uploads') && mkdir(__COLA_DIR__.'/usr/uploads', 0777);

		include __COLA_DIR__ . "/var/install/view/finish.php";
		
		
		Plugins::refresh();
		
        exit;
		}
    }
}
?>